{% extends '1.html' %}
{% block content %}
<body>
    <div class="register-page-body">
        <div class="register-page-container">
            <div class="register-page-header">
                <h1>创建账户</h1>
                <p>加入我们，开启精彩旅程</p>
            </div>

            <div class="register-page-section">
                <h2 class="register-page-section-title">用户注册</h2>

                <div class="register-page-error-message" id="errorMessage"></div>
                <div class="register-page-success-message" id="successMessage"></div>

                <form id="registerForm">
                    <div class="register-page-form-row">
                        <div class="register-page-form-group">
                            <label class="register-page-form-label" for="firstName">
                                姓<span class="required">*</span>
                            </label>
                            <input type="text" id="firstName" class="register-page-form-input" placeholder="请输入姓" required>
                            <div class="register-page-form-error" id="firstNameError"></div>
                        </div>

                        <div class="register-page-form-group">
                            <label class="register-page-form-label" for="lastName">
                                名<span class="required">*</span>
                            </label>
                            <input type="text" id="lastName" class="register-page-form-input" placeholder="请输入名" required>
                            <div class="register-page-form-error" id="lastNameError"></div>
                        </div>
                    </div>

                    <div class="register-page-form-group">
                        <label class="register-page-form-label" for="username">
                            用户名<span class="required">*</span>
                        </label>
                        <input type="text" id="username" class="register-page-form-input" placeholder="请输入用户名（3-20个字符）" required>
                        <div class="register-page-form-help">用户名将作为您的唯一标识</div>
                        <div class="register-page-form-error" id="usernameError"></div>
                    </div>

                    <div class="register-page-form-group">
                        <label class="register-page-form-label" for="email">
                            邮箱地址<span class="required">*</span>
                        </label>
                        <input type="email" id="email" class="register-page-form-input" placeholder="请输入邮箱地址" required>
                        <div class="register-page-form-help">我们将向此邮箱发送验证邮件</div>
                        <div class="register-page-form-error" id="emailError"></div>
                    </div>

                    <div class="register-page-form-group">
                        <label class="register-page-form-label" for="phone">
                            手机号码
                        </label>
                        <input type="tel" id="phone" class="register-page-form-input" placeholder="请输入手机号码">
                        <div class="register-page-form-error" id="phoneError"></div>
                    </div>

                    <div class="register-page-form-group">
                        <label class="register-page-form-label" for="password">
                            密码<span class="required">*</span>
                        </label>
                        <input type="password" id="password" class="register-page-form-input" placeholder="请输入密码（至少8个字符）" required>
                        <div class="register-page-password-strength">
                            <div class="register-page-password-strength-bar" id="passwordStrengthBar"></div>
                        </div>
                        <div class="register-page-form-help" id="passwordHelp">密码应包含字母、数字和特殊字符</div>
                        <div class="register-page-form-error" id="passwordError"></div>
                    </div>

                    <div class="register-page-form-group">
                        <label class="register-page-form-label" for="confirmPassword">
                            确认密码<span class="required">*</span>
                        </label>
                        <input type="password" id="confirmPassword" class="register-page-form-input" placeholder="请再次输入密码" required>
                        <div class="register-page-form-error" id="confirmPasswordError"></div>
                    </div>

                    <div class="register-page-form-checkbox">
                        <input type="checkbox" id="agreement" required>
                        <label for="agreement">
                            我已阅读并同意 <a href="#" onclick="showTerms(); return false;">用户协议</a> 和 <a href="#" onclick="showPrivacy(); return false;">隐私政策</a>
                        </label>
                    </div>

                    <div class="register-page-form-checkbox">
                        <input type="checkbox" id="newsletter">
                        <label for="newsletter">订阅我们的新闻通讯，获取最新资讯</label>
                    </div>

                    <button type="submit" class="register-page-btn" id="registerBtn">注 册</button>
                </form>

                <div class="register-page-login-link">
                    已有账户？ <a href="login.html">立即登录</a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 注册API配置
        // http://127.0.0.1:8000/shopper/logout/shopper/api/register/
        const RegisterAPI = {
            // 注册接口URL
            registerUrl: '/shopper/api/register/',
            // 请求超时时间（毫秒）
            timeout: 10000
        };

        // 注册管理器
        const RegisterManager = {
            // 初始化
            init: function() {
                this.bindEvents();
                this.initializeValidation();
            },

            // 绑定事件
            bindEvents: function() {
                const form = document.getElementById('registerForm');
                if (form) {
                    form.addEventListener('submit', this.handleSubmit.bind(this));
                }

                // 实时验证
                const inputs = document.querySelectorAll('.register-page-form-input');
                inputs.forEach(input => {
                    input.addEventListener('blur', this.validateField.bind(this));
                    input.addEventListener('input', this.clearFieldError.bind(this));
                });

                // 密码强度检测
                const passwordInput = document.getElementById('password');
                if (passwordInput) {
                    passwordInput.addEventListener('input', this.checkPasswordStrength.bind(this));
                }
            },

            // 初始化验证
            initializeValidation: function() {
                this.validationRules = {
                    firstName: {
                        required: true,
                        minLength: 1,
                        maxLength: 20,
                        pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
                        message: '请输入有效的姓'
                    },
                    lastName: {
                        required: true,
                        minLength: 1,
                        maxLength: 20,
                        pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
                        message: '请输入有效的名'
                    },
                    username: {
                        required: true,
                        minLength: 3,
                        maxLength: 20,
                        pattern: /^[a-zA-Z0-9_]+$/,
                        message: '用户名只能包含字母、数字和下划线'
                    },
                    email: {
                        required: true,
                        pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                        message: '请输入有效的邮箱地址'
                    },
                    phone: {
                        required: false,
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入有效的手机号码'
                    },
                    password: {
                        required: true,
                        minLength: 6,
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)/,  // 只需要字母和数字
                        message: '密码必须包含字母和数字'
},
                    confirmPassword: {
                        required: true,
                        match: 'password',
                        message: '两次输入的密码不一致'
                    }
                };
            },

            // 处理表单提交
            handleSubmit: async function(e) {
                e.preventDefault();

                if (this.isLoading) return;

                // 验证所有字段
                if (!this.validateAllFields()) {
                    return;
                }

                // 检查协议
                if (!document.getElementById('agreement').checked) {
                    this.showError('请阅读并同意用户协议和隐私政策');
                    return;
                }

                // 显示加载状态
                this.setLoading(true);
                this.hideMessages();

                try {
                    // 收集表单数据
                    const formData = this.collectFormData();

                    // 发送注册请求
                    const response = await this.sendRegisterRequest(formData);

                    // 处理注册成功
                    this.handleRegisterSuccess(response.data);

                } catch (error) {
                    // 处理注册失败
                    this.handleRegisterError(error);
                } finally {
                    this.setLoading(false);
                }
            },

            // 收集表单数据
            collectFormData: function() {
                return {
                    firstName: document.getElementById('firstName').value.trim(),
                    lastName: document.getElementById('lastName').value.trim(),
                    username: document.getElementById('username').value.trim(),
                    email: document.getElementById('email').value.trim(),
                    phone: document.getElementById('phone').value.trim(),
                    password: document.getElementById('password').value,
                    newsletter: document.getElementById('newsletter').checked
                };
            },

            // 发送注册请求
            sendRegisterRequest: async function(formData) {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), RegisterAPI.timeout);

                try {
                    const response = await fetch(RegisterAPI.registerUrl, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify(formData),
                        signal: controller.signal
                    });

                    clearTimeout(timeoutId);

                    if (!response.ok) {
                        const errorData = await response.json().catch(() => ({}));
                        throw new Error(errorData.message || `HTTP ${response.status}: ${response.statusText}`);
                    }

                    return await response.json();

                } catch (error) {
                    clearTimeout(timeoutId);

                    if (error.name === 'AbortError') {
                        throw new Error('请求超时，请检查网络连接');
                    }

                    if (error instanceof TypeError) {
                        throw new Error('网络连接失败，请检查网络设置');
                    }

                    throw error;
                }
            },

            // 处理注册成功
            handleRegisterSuccess: function(data) {
                this.showSuccess('注册成功！正在跳转到登录页面...');

                // 清空表单
                document.getElementById('registerForm').reset();

                // 3秒后跳转到登录页面
                setTimeout(() => {
                    window.location.href = 'http://127.0.0.1:8000/shopper/login/';
                }, 3000);
            },

            // 处理注册错误
            handleRegisterError: function(error) {
                console.error('注册错误:', error);

                let errorMessage = '注册失败，请重试';
                let fieldError = null;

                if (error.message) {
                    // 根据后端返回的错误信息进行分类处理
                    if (error.message.includes('用户名已存在') || error.message.includes('username')) {
                        errorMessage = '用户名已存在';
                        fieldError = { field: 'username', message: errorMessage };
                    } else if (error.message.includes('邮箱已存在') || error.message.includes('email')) {
                        errorMessage = '邮箱已被注册';
                        fieldError = { field: 'email', message: errorMessage };
                    } else if (error.message.includes('手机号已存在') || error.message.includes('phone')) {
                        errorMessage = '手机号已被注册';
                        fieldError = { field: 'phone', message: errorMessage };
                    } else if (error.message.includes('400') || error.message.includes('格式') || error.message.includes('无效')) {
                        errorMessage = '数据格式错误，请检查输入';
                    } else if (error.message.includes('429') || error.message.includes('频率')) {
                        errorMessage = '注册频率过高，请稍后再试';
                    } else if (error.message.includes('网络')) {
                        errorMessage = error.message;
                    } else {
                        errorMessage = error.message;
                    }
                }

                // 如果是字段错误，显示在对应字段下
                if (fieldError) {
                    const field = document.getElementById(fieldError.field);
                    const errorElement = document.getElementById(fieldError.field + 'Error');
                    if (field && errorElement) {
                        this.showFieldError(field, errorElement, fieldError.message);
                    }
                } else {
                    // 否则显示全局错误
                    this.showError(errorMessage);
                    this.shakeForm();
                }
            },

            // 验证所有字段
            validateAllFields: function() {
                const fields = ['firstName', 'lastName', 'username', 'email', 'phone', 'password', 'confirmPassword'];
                let isValid = true;

                fields.forEach(field => {
                    if (!this.validateField({ target: document.getElementById(field) })) {
                        isValid = false;
                    }
                });

                return isValid;
            },

            // 验证单个字段
            validateField: function(e) {
                const field = e.target;
                const fieldName = field.id;
                const value = field.value.trim();
                const rule = this.validationRules[fieldName];

                if (!rule) return true;

                const errorElement = document.getElementById(fieldName + 'Error');

                // 必填验证
                if (rule.required && !value) {
                    this.showFieldError(field, errorElement, '此字段为必填项');
                    return false;
                }

                // 如果字段为空且非必填，跳过验证
                if (!value && !rule.required) {
                    this.clearFieldError({ target: field });
                    return true;
                }

                // 长度验证
                if (rule.minLength && value.length < rule.minLength) {
                    this.showFieldError(field, errorElement, `最少需要${rule.minLength}个字符`);
                    return false;
                }

                if (rule.maxLength && value.length > rule.maxLength) {
                    this.showFieldError(field, errorElement, `最多允许${rule.maxLength}个字符`);
                    return false;
                }

                // 正则验证
                if (rule.pattern && !rule.pattern.test(value)) {
                    this.showFieldError(field, errorElement, rule.message);
                    return false;
                }

                // 密码匹配验证
                if (rule.match) {
                    const matchField = document.getElementById(rule.match);
                    if (matchField && value !== matchField.value) {
                        this.showFieldError(field, errorElement, rule.message);
                        return false;
                    }
                }

                // 验证通过
                this.clearFieldError({ target: field });
                return true;
            },

            // 显示字段错误
            showFieldError: function(field, errorElement, message) {
                field.classList.add('error');
                field.classList.remove('success');
                if (errorElement) {
                    errorElement.textContent = message;
                    errorElement.style.display = 'block';
                }
            },

            // 清除字段错误
            clearFieldError: function(e) {
                const field = e.target;
                const fieldName = field.id;
                const errorElement = document.getElementById(fieldName + 'Error');

                field.classList.remove('error');
                if (errorElement) {
                    errorElement.style.display = 'none';
                }
            },

            // 检查密码强度
            checkPasswordStrength: function(e) {
                const password = e.target.value;
                const strengthBar = document.getElementById('passwordStrengthBar');
                const passwordHelp = document.getElementById('passwordHelp');

                if (!password) {
                    strengthBar.className = 'register-page-password-strength-bar';
                    passwordHelp.textContent = '密码应包含字母、数字和特殊字符';
                    return;
                }

                let strength = 0;

                // 长度检查
                if (password.length >= 8) strength++;
                if (password.length >= 12) strength++;

                // 字符类型检查
                if (/[a-z]/.test(password)) strength++;
                if (/[A-Z]/.test(password)) strength++;
                if (/\d/.test(password)) strength++;
                if (/[@$!%*?&]/.test(password)) strength++;

                // 更新强度条
                strengthBar.className = 'register-page-password-strength-bar';
                if (strength <= 2) {
                    strengthBar.classList.add('weak');
                    passwordHelp.textContent = '密码强度：弱';
                    passwordHelp.style.color = '#d32f2f';
                } else if (strength <= 4) {
                    strengthBar.classList.add('medium');
                    passwordHelp.textContent = '密码强度：中等';
                    passwordHelp.style.color = '#f57c00';
                } else {
                    strengthBar.classList.add('strong');
                    passwordHelp.textContent = '密码强度：强';
                    passwordHelp.style.color = '#388e3c';
                }
            },

            // 设置加载状态
            setLoading: function(loading) {
                this.isLoading = loading;
                const registerBtn = document.getElementById('registerBtn');
                const inputs = document.querySelectorAll('.register-page-form-input');

                if (loading) {
                    registerBtn.classList.add('register-page-btn-loading');
                    registerBtn.disabled = true;
                    inputs.forEach(input => input.disabled = true);
                } else {
                    registerBtn.classList.remove('register-page-btn-loading');
                    registerBtn.disabled = false;
                    inputs.forEach(input => input.disabled = false);
                }
            },

            // 显示错误消息
            showError: function(message) {
                const errorMsg = document.getElementById('errorMessage');
                if (errorMsg) {
                    errorMsg.textContent = message;
                    errorMsg.style.display = 'block';
                }
            },

            // 显示成功消息
            showSuccess: function(message) {
                const successMsg = document.getElementById('successMessage');
                if (successMsg) {
                    successMsg.textContent = message;
                    successMsg.style.display = 'block';
                }
            },

            // 隐藏所有消息
            hideMessages: function() {
                const errorMsg = document.getElementById('errorMessage');
                const successMsg = document.getElementById('successMessage');
                if (errorMsg) errorMsg.style.display = 'none';
                if (successMsg) successMsg.style.display = 'none';
            },

            // 表单抖动效果
            shakeForm: function() {
                const form = document.querySelector('.register-page-section');
                if (form) {
                    form.style.animation = 'registerPageShake 0.5s';
                    setTimeout(() => {
                        form.style.animation = '';
                    }, 500);
                }
            }
        };

        // 显示用户协议
        function showTerms() {
            alert('用户协议内容\n\n这里是用户协议的详细内容...');
        }

        // 显示隐私政策
        function showPrivacy() {
            alert('隐私政策内容\n\n这里是隐私政策的详细内容...');
        }

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes registerPageShake {
                0%, 100% { transform: translateX(0); }
                10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
                20%, 40%, 60%, 80% { transform: translateX(5px); }
            }
            @keyframes registerPageSpin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
        `;
        document.head.appendChild(style);

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            RegisterManager.init();
        });

        // 导出注册管理器供其他脚本使用
        window.RegisterManager = RegisterManager;
    </script>
</body>
{% endblock content %}